package site.ycsyxt.web.core;

import lombok.extern.slf4j.Slf4j;
import site.ycsyxt.common.util.DateUtils;
import site.ycsyxt.framework.service.MailService;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author ycs(15241496739 @ 163.com)
 * @date 2021/11/21
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Autowired
    private MailService mailService;

    /**
     * 运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生运行时异常.", requestURI, e);
        mailService.send("15241496739@163.com",
                "【异常报警】发生系统异常, 日期: " + DateUtils.parseTimeStampToStr(System.currentTimeMillis()),
                "请求地址: " + requestURI + ", error: " + e.getMessage());
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        mailService.send("15241496739@163.com",
                "【异常报警】发生系统异常, 日期: " + DateUtils.parseTimeStampToStr(System.currentTimeMillis()),
                "请求地址: " + requestURI + ", error: " + e.getMessage());
        return AjaxResult.error(e.getMessage());
    }
}
